import * as echarts from 'echarts';
import {LitElement, html, TemplateResult} from 'lit';
import {customElement, property} from "lit/decorators.js";
import style from '../echarts.css.ts';

export interface BarYProps {
    chartId?: string;
    width?: string;
    height?: string;
    title?: object;
    tooltip?: object;
    legend?: string[];
    grid?: object;
    yAxisData?: string[];
    seriesData?: number[][];
}

@customElement('lit-bar-y')
export class LitBarY extends LitElement {
    @property({type: String}) chartId: string = 'lit-bar-y-chart';
    @property({type: String}) width: string = '600px';
    @property({type: String}) height: string = '400px';
    @property({type: Object}) title: any = {text: 'World Population'};
    @property({type: Object}) tooltip: any = {
        trigger: 'axis',
        axisPointer: {
            type: 'shadow'
        }
    };
    @property({type: Array}) legend: string[] = ['2011', '2012'];
    @property({type: Object}) grid: any = {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
    };
    @property({type: Array}) yAxisData: string[] = ['Brazil', 'Indonesia', 'USA', 'India', 'China', 'World'];
    @property({type: Array}) seriesData: number[][] = [
        [18203, 23489, 29034, 104970, 131744, 630230],
        [19325, 23438, 31000, 121594, 134141, 681807]
    ];

    getSeries(): any[] {
        return this.seriesData.map((data, index) => ({
            name: this.legend[index] || undefined,
            type: 'bar',
            data: data
        }));
    }

    option: echarts.EChartsOption = {
        title: this.title,
        tooltip: this.tooltip,
        legend: {
            data: this.legend,
        },
        grid: this.grid,
        xAxis: {
            type: 'value',
            boundaryGap: [0, 0.01]
        },
        yAxis: {
            type: 'category',
            data: this.yAxisData,
        },
        series: this.getSeries(),
    };

    static styles = style;

    updated() {
        this.option.title = this.title;
        this.option.tooltip = this.tooltip;
        (this.option.legend as any).data = this.legend;
        this.option.grid = this.grid;
        (this.option.yAxis as any).data = this.yAxisData;
        this.option.series = this.getSeries();
        this.firstUpdated();
    }

    firstUpdated() {
        const chart = echarts.init(this.shadowRoot!.getElementById(this.chartId)!);
        chart.setOption(this.option);
    }

    render(): TemplateResult {
        return html`<div id="${this.chartId}" style="width: ${this.width}; height: ${this.height};"></div>`;
    }
}

declare global {
    interface HTMLElementTagNameMap {
        'lit-bar-y': LitBarY;
    }
}